---

- name: Ставим пакеты из репозитория
  apt:
    name:
      - etcd-server
      - etcd-client
      - golang-etcd-server-dev
    state: present
    update_cache: yes
  notify:
    - Stop etcd

- name: Копируем конфиг первой ноды
  template:
    src: templates/etcd.conf.j2
    dest: /etc/default/etcd
    owner: root
    group: root
    mode: 0755

- name: Редактируем конфиг первой ноды
  lineinfile:
    path: /etc/default/etcd
    regexp: '^ETCD_INITIAL_CLUSTER=.*$'
    line: 'ETCD_INITIAL_CLUSTER="node1=http://10.0.0.50:2380"'
    backrefs: yes
  when: inventory_hostname == 'node1'

- name: dsfs
  lineinfile:
    path: /etc/default/etcd
    regexp: '^(ETCD_INITIAL_CLUSTER_STATE=).*$'
    line: 'ETCD_INITIAL_CLUSTER_STATE="new"'
    backrefs: yes
  when: inventory_hostname == 'node1'
  notify: Restart etcd

- name: Добавляем вторую ноду
  shell: sudo etcdctl member add node2 --peer-urls=http://10.0.0.51:2380
  when: inventory_hostname == 'node1'

- name: Редактируем конфиг второй ноды
  lineinfile:
    path: /etc/default/etcd
    regexp: '^(ETCD_INITIAL_CLUSTER=).*$'
    line: 'ETCD_INITIAL_CLUSTER="node1=http://10.0.0.50:2380,node2=http://10.0.0.51:2380"'
    backrefs: yes
  when: inventory_hostname == 'node2'
  notify: Restart etcd

- name: Добавляем третью ноду
  shell: sudo etcdctl member add node3 --peer-urls=http://10.0.0.52:2380
  when: inventory_hostname == 'node1'
  notify: Restart etcd

- name: Обновляем конфиг первой ноды
  template:
    src: templates/etcd.conf.j2
    dest: /etc/default/etcd
    owner: root
    group: root
    mode: 0755
  when: inventory_hostname == 'node1'
  notify: Restart etcd

- name: Обновляем конфиг второй ноды
  template:
    src: templates/etcd.conf.j2
    dest: /etc/default/etcd
    owner: root
    group: root
    mode: 0755
  when: inventory_hostname == 'node2'
  notify: Restart etcd

# - name: Проверяем состояние кластера
#   shell: sudo etcdctl -w table endpoint --cluster status
#   register: etcd_cluster_status

# - name: Выводим состояние кластера
#   debug:
#     var: etcd_cluster_status.stdout
